package com.cn.steam.iam.config;

import com.cn.steam.foundation.common.web.config.jwt.CommonAccessDeniedHandler;
import com.cn.steam.foundation.common.web.config.jwt.CommonAuthenticationEntryPoint;
import com.cn.steam.iam.service.Oauth2ClientDetailService;
import com.cn.steam.iam.service.Oauth2UserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

/**
 * @author: zjm
 * @create: 2021-11-20 12:57
 **/
@EnableAuthorizationServer
@Configuration
public class IamAuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private Oauth2UserDetailService oauth2UserDetailService;

    @Autowired
    private CommonAuthenticationEntryPoint commonAuthenticationEntryPoint;

    @Autowired
    private CommonAccessDeniedHandler commonAccessDeniedHandler;

    @Autowired
    private Oauth2ClientDetailService oauth2ClientDetailService;

    @Autowired
    private JwtAccessTokenConverter jwtAccessTokenConverter;

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.authenticationEntryPoint(commonAuthenticationEntryPoint)
                .accessDeniedHandler(commonAccessDeniedHandler);
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.withClientDetails(oauth2ClientDetailService);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore)
                .authenticationManager(authenticationManager)
                .userDetailsService(oauth2UserDetailService)
                .accessTokenConverter(jwtAccessTokenConverter);
    }
}
